package team.seekers.skill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import team.seekers.skill.entity.dao.Skill;
import team.seekers.skill.entity.dao.UserSkill;
import team.seekers.skill.entity.query.SkillQuery;
import team.seekers.skill.entity.vo.admin.add.AdminChapterAddVO;
import team.seekers.skill.entity.vo.admin.add.AdminSkillAddVO;
import team.seekers.skill.entity.vo.admin.list.AdminSkillListVO;
import team.seekers.skill.entity.vo.admin.update.AdminChapterUpdateVO;
import team.seekers.skill.entity.vo.admin.update.AdminSkillUpdateVO;
import team.seekers.skill.entity.vo.fore.detail.SkillDetailVO;
import team.seekers.skill.entity.vo.fore.list.SkillListVO;
import team.seekers.skill.mapper.SkillMapper;
import team.seekers.skill.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import team.seekers.skill.common.utils.SkillUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hbc
 * @since 2021-01-18
 */
@Service
public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements SkillService {

    @Autowired
    private ChapterService chapterService;
    @Autowired
    private SectionService sectionService;
    @Autowired
    private SkillCommentService skillCommentService;
    @Autowired
    private UserSkillService userSkillService;
    @Autowired
    private UserSeekSkillService userSeekSkillService;

    //后台技能增加
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean add(AdminSkillAddVO skillDo) {
        Skill skill = new Skill();
        BeanUtils.copyProperties(skillDo,skill);
        if(skillDo.getAdminChapterAddVOList() != null){
            skill.setChapters(skillDo.getAdminChapterAddVOList().size());
            Integer total = 0;
            for (AdminChapterAddVO chapterDo : skillDo.getAdminChapterAddVOList()) {
                total+=chapterDo.getAdminSectionAddVOList().size();
            }
            skill.setSections(total);
        }
        boolean save = save(skill);
        if (!save){
            return false;
        }
        if(skillDo.getAdminChapterAddVOList() != null){
            List<AdminChapterAddVO> chapterDoList = skillDo.getAdminChapterAddVOList();
            for (AdminChapterAddVO chapterDo : chapterDoList) {
                chapterDo.setSkillId(skill.getId());
                save = chapterService.add(chapterDo);
                if(!save)
                    return false;
            }
        }
        return true;
    }

    //后台技能删除
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean delete(String skillId) {
        //删除所有的章（顺带删除了所有的节、节的笔记、节的提问）
        boolean b = chapterService.removeBySkillId(skillId);
        if (!b){
            return false;
        }
        //删除评论
        boolean b1 = skillCommentService.removeBySkillId(skillId);
        if(!b1){
            return false;
        }
        //删除用户在该技能的学习记录
        boolean b2 = userSkillService.removeBySkillId(skillId);
        if (!b2){
            return false;
        }
        boolean b3 = removeById(skillId);
        return b3;
    }

    //后台技能更新（只能更新相关信息不能直接删除章节之类）
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean update(AdminSkillUpdateVO adminSkillUpdateVO) {
        Skill skill = new Skill();
        BeanUtils.copyProperties(adminSkillUpdateVO,skill);
        boolean update = updateById(skill);
        return update;
    }

    //后台编辑页数据渲染用
    @Override
    public AdminSkillUpdateVO getAdminSkillVO(String skillId) {
        AdminSkillUpdateVO adminSkillUpdateVO = new AdminSkillUpdateVO();
        Skill skill = getById(skillId);
        BeanUtils.copyProperties(skill,adminSkillUpdateVO);
        List<AdminChapterUpdateVO> list = chapterService.listAdminChapterUpdateVOBySkillId(skillId);
        adminSkillUpdateVO.setAdminChapterUpdateVOList(list);
        return adminSkillUpdateVO;
    }

    //前台详情页数据渲染
    @Override
    public SkillDetailVO getSkillDetailVO(String skillId) {
        SkillDetailVO skillVo = new SkillDetailVO();
        Skill byId = getById(skillId);
        if(byId == null){
            return null;
        }
        BeanUtils.copyProperties(byId,skillVo);
        Integer status = userSkillService.getStatus(SkillUtils.getUserId(), skillId);
        skillVo.setStatus(status);
        return skillVo;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean startLearn(String skillId, String userId) {
        UserSkill userSkill = new UserSkill();
        userSkill.setStatus(1);
        userSkill.setUserId(userId);
        userSkill.setSkillId(skillId);
        boolean save = userSkillService.save(userSkill);
        if (!save)
            return false;
        Skill skill = getById(skillId);
        boolean start = userSeekSkillService.addStartByType(userId, skill.getType());
        return start;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean endLearn(String skillId, String userId) {
        QueryWrapper<UserSkill> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("skill_id",skillId);
        UserSkill userSkill = userSkillService.getOne(wrapper);
        userSkill.setStatus(2);
        boolean update = userSkillService.updateById(userSkill);
        if (!update)
            return false;
        Skill skill = getById(skillId);
        boolean end = userSeekSkillService.addEndByType(userId, skill.getType());
        return end;
    }

    @Override
    public Map<String, Object> pageSkillCondition(long current, long limit, SkillQuery skillQuery) {
        Page<Skill> pageSkill = new Page<>(current,limit);
        QueryWrapper<Skill> wrapper = new QueryWrapper<>();
        String name = skillQuery.getName();
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        String type = skillQuery.getType();
        if (!StringUtils.isEmpty(type)){
            if (SkillUtils.isTrueType(type)){
                wrapper.eq("type",type);
            }
        }
        String begin = skillQuery.getBegin();
        if(!StringUtils.isEmpty(begin)){
            wrapper.ge("update_date",begin);
        }
        String end = skillQuery.getEnd();
        if (!StringUtils.isEmpty(end)){
            wrapper.le("update_date",end);
        }
        //以热度排序
        updateSkillsHeat();
        wrapper.orderByAsc("heat");
        page(pageSkill, wrapper);
        Long total = pageSkill.getTotal();
        List<Skill> records = pageSkill.getRecords();
        if (records == null){
            return null;
        }
        List<SkillListVO> skillVOList = new ArrayList<>();
        //获取存放的userId
        for (Skill record : records){
            SkillListVO skillVO = new SkillListVO();
            BeanUtils.copyProperties(record,skillVO);
            //确认用户在该技能的学习情况
            Integer status = userSkillService.getStatus(SkillUtils.getUserId(), record.getId());
            skillVO.setStatus(status);
            skillVOList.add(skillVO);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("rows",skillVOList);
        return map;
    }

    @Override
    public Map<String, Object> adminPageSkillCondition(int current, int limit, SkillQuery skillQuery) {
        Page<Skill> pageSkill = new Page<>(current,limit);
        QueryWrapper<Skill> wrapper = new QueryWrapper<>();
        String name = skillQuery.getName();
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        String type = skillQuery.getType();
        if (!StringUtils.isEmpty(type)){
            if (SkillUtils.isTrueType(type)){
                wrapper.eq("type",type);
            }
        }
        String begin = skillQuery.getBegin();
        if(!StringUtils.isEmpty(begin)){
            wrapper.ge("update_date",begin);
        }
        String end = skillQuery.getEnd();
        if (!StringUtils.isEmpty(end)){
            wrapper.le("update_date",end);
        }
        page(pageSkill, wrapper);
        Long total = pageSkill.getTotal();
        List<Skill> records = pageSkill.getRecords();
        if (records == null){
            return null;
        }
        List<AdminSkillListVO> adminSkillListVOS = new ArrayList<>();
        //获取存放的userId
        for (Skill record : records){
            AdminSkillListVO skillVO = new AdminSkillListVO();
            BeanUtils.copyProperties(record,skillVO);
            adminSkillListVOS.add(skillVO);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("rows",adminSkillListVOS);
        return map;
    }

    //更新所有字段的heat值
    @Transactional(rollbackFor=Exception.class)
    public void updateSkillsHeat(){
        Date now=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date currentDate = sdf.parse(sdf.format(now));
            QueryWrapper<Skill> wrapper = new QueryWrapper<>();
            List<Skill> skillList = baseMapper.selectList(wrapper);
            for(Skill skill:skillList){
                String v = setSkillHot(skill, currentDate);
                skill.setHeat(v);
                baseMapper.updateById(skill);
            }
        } catch (ParseException e){
            e.printStackTrace();
        }
    }

    //热度排行算法
    public String setSkillHot(Skill skill, Date currentDate) {
        double star = Double.parseDouble(skill.getStar());
        Integer comments = skill.getComments();
        Integer learnAmount = skill.getLearnAmount();
        Integer finishAmount = skill.getFinishAmount();
        Integer questionAmount = skill.getQuestionAmount();
        Date createDate = skill.getCreateDate();
        float v = SkillUtils.differentDaysByMillisecond(createDate, currentDate);
        double heat = (star+comments*1.5+learnAmount+finishAmount*5+questionAmount*2+1) / Math.pow((v + 2), 1.8);
        return heat+"";
    }

}
